﻿using System;
using System.Net;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using SoftwareApproach.TestingExtensions;

namespace ProxyFinder.Tests {
    [TestClass]
    public class BaseProxyFinderTests {

        [TestMethod]
        public void ProxyFinder_Create() {
            new BaseProxyFinder().ShouldNotBeNull();
        }

        [TestMethod]
        public void ProxyFinder_GetProxy_ShouldThrowNullReference_OnNullUri() {
            Testing.ShouldThrowException<ArgumentNullException>(() => new BaseProxyFinder().GetProxy(null));
        }

        [TestMethod]
        public void ProxyFinder_GetProxy_ShouldReturn_Null_IfSystemProxyIsNotSet() {
            IProxyFinder proxyFinder = new BaseProxyFinder();
            Uri uri = new Uri("http://www.google.com");
            IWebProxy proxy = proxyFinder.GetProxy(uri);
            if(!IsSystemProxySet(uri)) {
                proxy.ShouldBeNull();
            }
            else {
                proxy.ShouldNotBeNull();
            }
        }

        [TestMethod]
        public void ProxyFinder_ShouldReturn_NullWhenDefaultCredentialProviderIsUsed() {
            IProxyFinder proxyFinder = new BaseProxyFinder();
            IWebProxy systemProxy = WebRequest.DefaultWebProxy;
            WebRequest.DefaultWebProxy = new WebProxy("http://server/");
            proxyFinder.GetProxy(new Uri("http://www.google.com")).ShouldBeNull();
            WebRequest.DefaultWebProxy = systemProxy;
        }

        [TestMethod]
        public void ProxyFinder_ShouldReturn_SomethingIfWindowsCredentialsIsUsed() {
            IProxyFinder proxyFinder = new BaseProxyFinder();
            IWebProxy systemProxy = WebRequest.DefaultWebProxy;
            WebRequest.DefaultWebProxy = new WebProxy("http://server/");
            proxyFinder.GetProxy(new Uri("http://www.google.com")).ShouldBeNull();
            WebRequest.DefaultWebProxy = systemProxy;

        }
        private static bool IsSystemProxySet(Uri uri) {
            IWebProxy proxy = WebRequest.DefaultWebProxy;
            if(null != proxy) {
                Uri proxyAddress = new Uri(proxy.GetProxy(uri).AbsoluteUri);
                if(string.Equals(proxyAddress.AbsoluteUri, uri.AbsoluteUri)) {
                    return false;
                }
                bool bypassUri = proxy.IsBypassed(uri);
                if(bypassUri) {
                    return false;
                }
                proxy = new WebProxy(proxyAddress);
            }

            return null != proxy;
        }

    }
}
